import sanitizeHtml from 'sanitize-html';

export const handleBilibiliMedia = (match: RegExpExecArray) => {
  if (!match[1]) {
    return '无法加载该媒体';
  }

  try {
    return handelIframeHtml(
      match,
      `https://player.bilibili.com/player.html?bvid=${match[1]}`
    );
  } catch (e) {
    return '无法加载该媒体';
  }
};

export const handleTencentMedia = (match: RegExpExecArray) => {
  if (!match[1]) {
    return '无法加载该媒体';
  }

  try {
    return handelIframeHtml(
      match,
      `https://v.qq.com/txp/iframe/player.html?vid=${match[1]}`
    );
  } catch (e) {
    return '无法加载该媒体';
  }
};

export const handleYoukuMedia = (match: RegExpExecArray) => {
  if (!match[1]) {
    return '无法加载该媒体';
  }

  try {
    return handelIframeHtml(
      match,
      `https://player.youku.com/embed/${match[1]}`
    );
  } catch (e) {
    return '无法加载该媒体';
  }
};

export const handleIqiyiMedia = (match: RegExpExecArray) => {
  if (match[1]) {
    return '无法加载该媒体';
  }

  try {
    return handelIframeHtml(match, 'input');
  } catch (e) {
    return '无法加载该媒体';
  }
};

const handelIframeHtml = (match: RegExpExecArray, src: string | 'input') => {
  const url = new URL(`https://${match.input}`);
  let width = url.searchParams.get('width') || '';
  let height = url.searchParams.get('height') || '';

  if (src === 'input') {
    const html = sanitizeHtml(match.input, {
      allowedIframeHostnames: ['open.iqiyi.com'],
      allowedTags: ['iframe'],
      allowedAttributes: {
        iframe: ['src', 'width', 'height'],
      },
    });
    if (!html) {
      return '无法加载该媒体';
    }

    const srcExec = /src="(.+)"/.exec(html.split(' ')[1]);
    if (srcExec && srcExec[1]) {
      const split = srcExec[1].split(' ');
      if (split && split[0]) {
        src = split[0];
      }
    }

    const widthExec = /width="(\d+)"/.exec(html);
    if (widthExec && widthExec[1]) {
      width = widthExec[1];
    }

    const heightExec = /height="(\d+)"/.exec(html);
    if (heightExec && heightExec[1]) {
      height = heightExec[1];
    }
  }

  if (!/^https:\/\/.+/.test(src)) {
    return '无法加载该媒体';
  }

  if (/^\d+$/.test(width) && /^\d+$/.test(height)) {
    return (
      '<div>' +
      `<iframe width="${width}" height="${height}" class="iframe"` +
      ` src="${src}"` +
      ' allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"' +
      ' allowfullscreen> </iframe></div>'
    );
  }

  return (
    `<div class="ratio ratio-16x9">` +
    `<iframe class="iframe"` +
    ` src="${src}"` +
    ' allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"' +
    ' allowfullscreen> </iframe></div>'
  );
};
